package com.wdh.kjs.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.ListViewForScrollView;
import com.wdh.kjs.MainActivity;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

import java.util.List;

/**
 * Created by feifei on 2016/4/28.
 */
public class LoginActivity extends BaseTopActivity implements View.OnClickListener {

    private Button registerNow;
    private TextView forgetPassword;
    private Intent intent;
    public ImageView returnBack;
    private Button login;
    private JsonModel jsonModel;
    private EditText login_edit;
    private EditText login_edit1;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String back;
    private Boolean status = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginactivity);
        back = getIntent().getStringExtra("state");
        initview();
        initwidge();
    }

    private void initwidge() {
        returnBack.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    private void initview() {

        registerNow = (Button) findViewById(R.id.registerNow);
        registerNow.setOnClickListener(this);
        forgetPassword = (TextView) findViewById(R.id.forgetPassword);
        forgetPassword.setOnClickListener(this);
        returnBack = (ImageView) findViewById(R.id.returnBack);
        login = (Button) findViewById(R.id.login);
        login_edit = (EditText) findViewById(R.id.login_edit);
        login_edit1 = (EditText) findViewById(R.id.login_edit1);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.registerNow:
                intent = new Intent(this, RegisterNowActivity.class);
                startActivity(intent);
                break;
            case R.id.forgetPassword:
                intent = new Intent(this, ForgetPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.returnBack:
                finish();
                break;
            case R.id.login:
//                if(status){
//                    login.setBackgroundColor(getResources().getColor(R.color.bt_blue_2));
//                    status=false;
//                }
                intweb();
        }

    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("USERNAME", login_edit.getText().toString());
        params.addBodyParameter("PASSWORD", login_edit1.getText().toString());
        final HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.secondCookieStore);
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_LOGIN, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {


                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                String m = jsonModel.getPartyId();
                if (jsonModel._LOGIN_PASSED_()) {


                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();
                    editor.putString("loginToken", jsonModel.getPartyId());
                    editor.putString("nickName", jsonModel.getNickName());
                    editor.putString("phoneNumber", jsonModel.getPhoneNumber());
                    editor.putString("levels", jsonModel.getLevels());
                    editor.putString("type", jsonModel.getType());
                    editor.putString("zhanghao", login_edit.getText().toString());
                    editor.putString("mima", login_edit1.getText().toString());
                    editor.commit();
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                } else if (jsonModel.get_ERROR_MESSAGE_().indexOf("has been disabled")!=-1){
                        ToastUtils.showShort(LoginActivity.this, "用户被封禁");
                    }

                else
                 if (jsonModel.get_ERROR_MESSAGE_().indexOf("incorrect")!=-1)
                    ToastUtils.showShort(LoginActivity.this, "密码错误");
                else if (jsonModel.get_ERROR_MESSAGE_().indexOf("found")!=-1)
                    ToastUtils.showShort(LoginActivity.this, "账号不存在");

                }


            @Override
            public void onFailure(HttpException error, String msg) {
                Log.i("gggggg", error.getExceptionCode() + msg + "");
                ToastUtils.showShort(LoginActivity.this, "网络异常！");
            }
        });

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//这里重写返回键

            if (back.equals("1")) {
                preferences = getSharedPreferences("logininfo", Context.MODE_PRIVATE);
                editor = preferences.edit();

                editor.putString("loginToken", "");
                editor.putString("nickName", "未登录");
                editor.putString("phoneNumber", "");
                editor.putString("levels", "");
                editor.commit();
                intent = new Intent();
                intent.setClass(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                startActivity(intent);
//                ActivityManager activityMgr = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE );
//                activityMgr.restartPackage(getPackageName());
//                android.os.Process.killProcess(android.os.Process.myPid());   //获取PID
//                System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
//                this.finish();
            } else
                finish();

            return true;
        }
        return false;
    }
}
